package upload;

//all Imports needed in this Servlet
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import util.FileCounter;
import util.FormatChecker;
import util.FileUnziper;

/**
 * @author cuche
 * @date 15.05.2014
 * 
 *       Servlet that handles the upload request from the FileUploadForm.jsp
 */
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
	private static final String SAVE_FOLDER = "/pics";
	private static final String TEMP_ZIP_FOLDER = "/temp/";
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// sends user back to the FileUploadForm page
		response.sendRedirect("NoFileGivenError.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// get file from the request
		Part filePart = request.getPart("file");
		ServletContext context = getServletContext();
		String appPath = context.getRealPath(SAVE_FOLDER);
		String fileNameOld = getFileName(filePart);

		String contentType = filePart.getContentType();
		System.out.println(contentType);
		// checks Format
		if (FormatChecker.checkFormat(contentType)) {
			InputStream fileContent = filePart.getInputStream();
			if (FormatChecker.isZipEclipse(contentType)
					|| FormatChecker.isZip_Browser(contentType)) {
				String fileNameNew = appPath + TEMP_ZIP_FOLDER + fileNameOld;
				File zipFile = FileUploader.uploadImage(fileNameNew,
						fileContent);
				FileUnziper.unzipFileTo(zipFile, appPath);
				zipFile.delete();

				String url = "/result.jsp"; // relative url for display jsp page
				ServletContext sc = getServletContext();
				RequestDispatcher rd = sc.getRequestDispatcher(url);
				try {
					rd.forward(request, response);
				} catch (IOException ex) {
					response.getWriter().append(ex.getLocalizedMessage());
				}

			} else {
				int counterValue = FileCounter.getInstance().getNextCounter();
				String fileNameNew = appPath + "/" + counterValue + "_"
						+ fileNameOld;
				// calling uploadImage method from FileUploader class
				FileUploader.uploadImage(fileNameNew, fileContent);

				String url = "/result.jsp"; // relative url for display jsp page
				ServletContext sc = getServletContext();
				RequestDispatcher rd = sc.getRequestDispatcher(url);
				try {
					rd.forward(request, response);
				} catch (IOException ex) {
					response.getWriter().append(ex.getLocalizedMessage());
				}
			}
		} else {
			response.sendRedirect("WrongFormatError.jsp");
		}

	}

	/**
	 * 
	 * @param part
	 * @return filename withouth the HTML header
	 */
	private String getFileName(Part part) {

		for (String cd : part.getHeader("content-disposition").split(";")) {
			if (cd.trim().startsWith("filename")) {
				String filename = cd.substring(cd.indexOf('=') + 1).trim()
						.replace("\"", "");
				return filename.substring(filename.lastIndexOf('/') + 1)
						.substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
			}
		}
		return null;
	}// END OF getFileName

}// END OF CLASS
